package com.cbank.controller.others;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cbank.constants.Result;
import com.cbank.constants.ResultCode;
import com.cbank.domain.DistinctPhone;
import com.cbank.service.DistinctPhoneService;
import com.cbank.utils.ExcelUtils;

@Controller
@RequestMapping("/excel")
public class DataChenController {
	Logger logger = Logger.getLogger(DataChenController.class);
	@Autowired
	DistinctPhoneService distinctPhoneService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String excelUploadPager(HttpServletResponse response, Model model) {
		return "/excel/exceldata";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String excelUpload(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam CommonsMultipartFile exceldata) {
		logger.info("/upload");
		// ArrayList<DistinctPhone> list = new ArrayList<>();
		int un = 0;// 不正常
		int n = 0;// 正常
		InputStream inputStream = null;

		try {
			inputStream = exceldata.getInputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			Workbook workBook = null;
			try {
				workBook = WorkbookFactory.create(inputStream);
			} catch (InvalidFormatException e) {
				e.printStackTrace();
			}
			Sheet sheet = workBook.getSheetAt(0);
			int count = 0;
			// 利用foreach循环 遍历sheet中的所有行
			for (Row row : sheet) {
				if (count != 0) {
					DistinctPhone distinctPhone = new DistinctPhone();
					// 遍历row中的所有方格
					for (int i = 0; i < 4; i++) {
						Cell cell = row.getCell(i);
						if (cell != null) {

							int cellType = cell.getCellType();
							String value = "";
							switch (cellType) {
							case Cell.CELL_TYPE_BLANK:
								value = "";
								break;
							case Cell.CELL_TYPE_BOOLEAN:
								value = cell.getBooleanCellValue() + "";
								break;
							case Cell.CELL_TYPE_ERROR:
								value = "error";
								break;
							case Cell.CELL_TYPE_FORMULA:
								value = "formula";
								break;
							case Cell.CELL_TYPE_NUMERIC:
								value = ((Double) (cell.getNumericCellValue())).longValue() + "";
								break;
							case Cell.CELL_TYPE_STRING:
								value = cell.getStringCellValue();
								break;
							default:
								value = "exception";
								break;
							}
							String v = value.trim();
							if (i == 0) {
								distinctPhone.setCompany(v);
							} else if (i == 1) {
								distinctPhone.setName(v);
							} else if (i == 2) {
								distinctPhone.setPhone(v);
							} else {
								distinctPhone.setRemark(v);
							}
						}
					}
					distinctPhone.setStatus(1);
					int status = distinctPhoneService.save(distinctPhone);
					if (status == 0) {
						// 正常
						n++;
					} else {
						// 重复数据
						un++;
					}
				}
				count++;
			}
			// 关闭输入流
			inputStream.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		int total = distinctPhoneService.getCount();
		Result<String> result = new Result<String>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(),
				"本次数据总数： " + (n + un) + "，导入数据： " + n + " 个，" + "重复数据： " + un + " 个，" + "数据库中数据总量：" + total);
		model.addAttribute("result", result);
		return "/excel/result";
	}

	@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
	public void excelExport(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<DistinctPhone> list = new ArrayList<DistinctPhone>(0);
		try {
			list = distinctPhoneService.getList(0, 300);
			for (int i = 0; i < list.size(); i++) {
				String phone = list.get(i).getPhone();
				distinctPhoneService.updateInvalid(phone);
			}
			ExcelUtils.exportExcel(list, response, request, "线索数据", new ExcelUtils.Callback<DistinctPhone>() {

				@Override
				public void setData(HSSFCell cell, int index, DistinctPhone distinctPhone) {
					switch (index) {
					case 0:
						cell.setCellValue(distinctPhone.getCompany());
						break;
					case 1:
						cell.setCellValue(distinctPhone.getName());
						break;
					case 2:
						cell.setCellValue(distinctPhone.getPhone());
						break;
					case 3:
						cell.setCellValue(distinctPhone.getRemark());
						break;
					default:
						break;
					}
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
